const db = require('../config/db');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { SECRET } = require('../middlewares/auth');
const { success, fail } = require('../utils/response');

exports.register = async (req, res) => {
  const { username, password, phone } = req.body;
  const [rows] = await db.query('SELECT id FROM User WHERE username=?', [username]);
  if (rows.length) return res.json(fail('用户名已存在'));
  const hash = await bcrypt.hash(password, 10);
  await db.query('INSERT INTO User (username, password, phone) VALUES (?, ?, ?)', [username, hash, phone]);
  res.json(success(null, '注册成功'));
};

exports.login = async (req, res) => {
  const { username, password } = req.body;
  const [rows] = await db.query('SELECT * FROM User WHERE username=?', [username]);
  if (!rows.length) return res.json(fail('用户不存在'));
  const user = rows[0];
  const isMatch = await bcrypt.compare(password, user.password);
  if (!isMatch) return res.json(fail('密码错误'));

  const token = jwt.sign({ id: user.id, username: user.username }, SECRET, { expiresIn: '7d' });
  res.json(success({ token, id: user.id, username: user.username, phone: user.phone, avatar: user.avatar, points: user.points }, '登录成功'));
};

exports.getInfo = async (req, res) => {
  const [rows] = await db.query('SELECT id, username, avatar, phone, points FROM User WHERE id=?', [req.user.id]);
  res.json(success(rows[0]));
};

exports.updateInfo = async (req, res) => {
  const { phone, points } = req.body;
  const updateFields = [];
  const values = [];

  if (phone) {
    updateFields.push('phone = ?');
    values.push(phone);
  }
  if (points !== undefined) {
    updateFields.push('points = ?');
    values.push(points);
  }

  if (updateFields.length === 0) {
    return res.json(fail('没有需要更新的字段'));
  }

  values.push(req.user.id);
  const query = `UPDATE User SET ${updateFields.join(', ')} WHERE id = ?`;
  await db.query(query, values);
  res.json(success());
};

exports.updateAvatar = async (req, res) => {
  try {
    if (!req.file) {
      return res.json(fail('请选择要上传的图片'));
    }
    const fs = require('fs');
    const mime = req.file.mimetype || 'image/jpeg';
    const base64 = fs.readFileSync(req.file.path, { encoding: 'base64' });
    const dataUri = `data:${mime};base64,${base64}`;

    await db.query('UPDATE User SET avatar=? WHERE id=?', [dataUri, req.user.id]);

    // 删除临时文件
    fs.unlink(req.file.path, (err) => {
      if (err) console.error('删除文件失败:', err);
    });

    res.json(success({ avatar: dataUri }));
  } catch (error) {
    // 删除上传的文件（如果存在）
    if (req.file) {
      fs.unlink(req.file.path, (err) => {
        if (err) console.error('删除文件失败:', err);
      });
    }
    res.json(fail(error.message || '上传头像失败'));
  }
};

// 新增：用户名/电话/密码更新（符合页面“用户名/旧密码/新密码/电话”）
exports.updateCredentials = async (req, res) => {
  try {
    const { username, phone, old_password, new_password, avatar } = req.body;

    const updates = [];
    const params = [];

    if (phone && typeof phone === 'string') {
      updates.push('phone = ?');
      params.push(phone);
    }

    if (username && typeof username === 'string') {
      const [exists] = await db.query('SELECT id FROM User WHERE username=? AND id<>?', [username, req.user.id]);
      if (exists.length) return res.json(fail('用户名已存在'));
      updates.push('username = ?');
      params.push(username);
    }

    // 新增：头像字符串更新（支持 http(s)、data:、或以 / 开头的相对路径）
    if (avatar && typeof avatar === 'string') {
      const s = avatar.trim();
      const valid = s.startsWith('http://') || s.startsWith('https://') || s.startsWith('data:') || s.startsWith('/');
      if (!valid) return res.json(fail('头像格式不合法'));
      updates.push('avatar = ?');
      params.push(s);
    }

    if (old_password || new_password) {
      if (!old_password || !new_password) {
        return res.json(fail('请同时提供旧密码与新密码'));
      }
      const [rows] = await db.query('SELECT password FROM User WHERE id=?', [req.user.id]);
      if (!rows.length) return res.json(fail('用户不存在'));
      const ok = await bcrypt.compare(old_password, rows[0].password);
      if (!ok) return res.json(fail('旧密码不正确'));
      const hash = await bcrypt.hash(new_password, 10);
      updates.push('password = ?');
      params.push(hash);
    }

    if (updates.length === 0) {
      return res.json(fail('没有需要更新的字段'));
    }

    params.push(req.user.id);
    await db.query(`UPDATE User SET ${updates.join(', ')}, updated_at=NOW() WHERE id=?`, params);

    const [rows2] = await db.query('SELECT id, username, avatar, phone, points FROM User WHERE id=?', [req.user.id]);
    res.json(success(rows2[0], '更新成功'));
  } catch (e) {
    res.json(fail(e.message || '更新失败'));
  }
};